package service

import (
	"context"
	"fmt"

	"hundsun.com/hsl/hschain/p2p/common/p2perror"
)

//Handler Handler
type Handler func(ctx context.Context, req interface{}) (interface{}, int32, error)

var (
	eventHandlers = make(map[string]Handler)
)

//RegisterHandler 注册Handler
func RegisterHandler(eventID string, handler Handler) {
	if handler == nil {
		panic(fmt.Sprintf("addEventHandler, handler is nil, id=%s", eventID))
	}
	if _, dup := eventHandlers[eventID]; dup {
		panic(fmt.Sprintf("addEventHandler, duplicate handler, id=%s, len=%d", eventID, len(eventHandlers)))
	}
	eventHandlers[eventID] = HandlerWithRecover(handler)
}

//HandlerWithRecover 执行Handler
func HandlerWithRecover(f Handler) Handler {
	return func(ctx context.Context, in interface{}) (interface{}, int32, error) {
		defer func() {
			if r := recover(); r != nil {
				p2perror.Log().Errorf("handle event panic, reason:%v", r)
			}
		}()
		return f(ctx, in)
	}
}

// GetEventHandler gets event handler by event ID.
func GetEventHandler(eventID string) Handler {
	return eventHandlers[eventID]
}
